<?php
include 'HZip.php';
include 'Word.php';
include "Classes/PHPExcel/IOFactory.php";
class table extends CI_Controller{
	
	public function __construct(){
		parent::__construct();
		
		if (!$this->session->userdata('LoggedIn')){
			redirect('login');
		}else{
			$this->load->model('tablemodel', 'table', TRUE);
			$this->load->library("pagination");
		}
	}
	
	
	public function index(){
		$data['id'] = $this->session->userdata('id');
		$data['name'] = $this->session->userdata('name');
		$data['image'] = $this->session->userdata('image');
		$data['date_of_birth'] = $this->session->userdata('date_of_birth');
		$data['role'] = $this->session->userdata('role');
		$data['address'] = $this->session->userdata('address');
		
		$config = array();
        $config["base_url"] = base_url() . "table/index";
        $config["total_rows"] = $this->table->table_count();
        $config["per_page"] = 10;
        $choice = $config["total_rows"] / $config["per_page"];
    	$config["num_links"] = round($choice);
		
		$this->pagination->initialize($config);
 
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data["results"] = $this->table->
            fetch_tables($config["per_page"], $page);
        $data["links"] = $this->pagination->create_links();
 		
		$this->load->view('table', $data);
	}
	
	public function create_new_table(){
		$data['id'] = $this->session->userdata('id');
		$data['name'] = $this->session->userdata('name');
		$data['image'] = $this->session->userdata('image');
		$data['date_of_birth'] = $this->session->userdata('date_of_birth');
		$data['role'] = $this->session->userdata('role');
		$data['address'] = $this->session->userdata('address');
		
		$manager_list = $this->table->manager_list();
		$data['manager_list'] = $manager_list;
		
		$data['isedit'] = false;
		
		if ($_POST){
			//load helper and library:
			$this->load->helper(array('form'));
			$this->load->library('form_validation');
			
			$this->form_validation->set_rules('text2', 'text2', 'required');
			$this->form_validation->set_rules('number8', 'number8', 'required|numberic');
			
			if ($this->form_validation->run() == FALSE){
					
			}else{
				$add_info['table_name'] = $_POST['text2'];
				$add_info['number'] = $_POST['number8'];
				$add_info['manager_id'] = intval($_POST['select4']);
				$add_info['status'] = 1;
				$add_info['description'] = $_POST['textarea5'];
				
				if ($_FILES["file6"]["name"]){
					if ($_FILES["file6"]["error"] > 0)
					  {
						  echo "Error: " . $_FILES["file6"]["error"] . "<br>";
					  }
					else
					  {
					  	  $url = explode("index.php", $_SERVER['PHP_SELF']);
						  $path = $_SERVER['DOCUMENT_ROOT'].$url[0]."assets/img/table";
						  if (!file_exists($path)) {
							   mkdir($path, 0777, true);
						  }
						  
						  $tmp_name = (explode(".",$_FILES['file6']['name']));
						  $name = $add_info['table_name'].".".strtolower($tmp_name[1]);
						  move_uploaded_file($_FILES["file6"]["tmp_name"],
					      $path."/".$name);
						  $add_info['image'] = $name;
						  
						  $this->add_zip_file($name);
					  }
				}
				
				$result = $this->table->create_new_table($add_info);
				if ($result){
					redirect('table');
				}
			}
		}
		
		$this->load->view('addtable', $data);
	}
	
	public function view_detail(){
		$data['id'] = $this->session->userdata('id');
		$data['name'] = $this->session->userdata('name');
		$data['image'] = $this->session->userdata('image');
		$data['date_of_birth'] = $this->session->userdata('date_of_birth');
		$data['role'] = $this->session->userdata('role');
		$data['address'] = $this->session->userdata('address');
		
		$table_id = $_GET['id'];
		
		$data['result'] = $this->table->table_detail($table_id);
		
		$this->load->view('tabledetail', $data);
	}
	
	public function edit_table(){
		$data['id'] = $this->session->userdata('id');
		$data['name'] = $this->session->userdata('name');
		$data['image'] = $this->session->userdata('image');
		$data['date_of_birth'] = $this->session->userdata('date_of_birth');
		$data['role'] = $this->session->userdata('role');
		$data['address'] = $this->session->userdata('address');
		
		$table_id = $_GET['id'];
		
		$table_info = $this->table->table_detail($table_id);
		
		$data['info'] = $table_info;
		
		$manager_list = $this->table->manager_list();
		$data['manager_list'] = $manager_list;
		
		$data['isedit'] = true;
		
		if ($_POST){
			//load helper and library:
			$this->load->helper(array('form'));
			$this->load->library('form_validation');
			
			$this->form_validation->set_rules('text2', 'text2', 'required');
			$this->form_validation->set_rules('number8', 'number8', 'required|numberic');
			
			if ($this->form_validation->run() == FALSE){
					
			}else{
				$add_info['table_name'] = $_POST['text2'];
				$add_info['number'] = $_POST['number8'];
				$add_info['manager_id'] = intval($_POST['select4']);
				$add_info['description'] = $_POST['textarea5'];
				
				if ($_FILES["file6"]["name"]){
					if ($_FILES["file6"]["error"] > 0)
					  {
						  echo "Error: " . $_FILES["file6"]["error"] . "<br>";
					  }
					else
					  {
					  	  $url = explode("index.php", $_SERVER['PHP_SELF']);
						  $path = $_SERVER['DOCUMENT_ROOT'].$url[0]."assets/img/table";
						  if (!file_exists($path)) {
							   mkdir($path, 0777, true);
						  }
						  
						  $tmp_name = (explode(".",$_FILES['file6']['name']));
						  $name = $add_info['table_name'].".".strtolower($tmp_name[1]);
						  move_uploaded_file($_FILES["file6"]["tmp_name"],
					      $path."/".$name);
						  $add_info['image'] = $name;
						  
						  $this->add_zip_file($name);
						  
						  $result = $this->table->update_table($table_id, $add_info);
						  redirect('table');
					  }
				}
				
				$result = $this->table->update_table($table_id, $add_info);
				if ($result){
					redirect('table');
				}
			}
		}
		
		$this->load->view('addtable', $data);
	}
	
	public function delete_table(){
		$table_id = $_GET['id'];
		
		$data['id'] = $this->session->userdata('id');
		$data['name'] = $this->session->userdata('name');
		$data['image'] = $this->session->userdata('image');
		$data['date_of_birth'] = $this->session->userdata('date_of_birth');
		$data['role'] = $this->session->userdata('role');
		$data['address'] = $this->session->userdata('address');
		$data['table_id'] = $table_id;
		
		$this->load->view('deletetable', $data);
	}
	
	public function delete(){
		$table_id = $_GET['id'];
		$this->table->delete_dish($table_id);
		redirect('table');
	}
	
	private function add_zip_file($file_name){
		$url = explode("index.php", $_SERVER['PHP_SELF']);
		$sourcePath = $_SERVER['DOCUMENT_ROOT'].$url[0]."assets/img/table";
		$outZipPath = $_SERVER['DOCUMENT_ROOT'].$url[0]."assets/img/table.zip";
		
		if (file_exists($outZipPath)){
			$zip = new ZipArchive();
			$zip->open($outZipPath);
			$zip->addFile($sourcePath."/".$file_name, "table/".$file_name);
			$zip->close();
		}else{
			HZip::zipDir($sourcePath, $outZipPath);
		}
	}
	
public function upload_multi_table(){
		$url = explode("index.php", $_SERVER['PHP_SELF']);
		$inputFileName = $_SERVER['DOCUMENT_ROOT'].$url[0]."file_upload/table/table.xls";
		//  Read your Excel workbook
		try {
		    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
		    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
		    $objPHPExcel = $objReader->load($inputFileName);
		} catch (Exception $e) {
		    die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
		}
		
		$rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
		$array_data = array();
		foreach ($rowIterator as $row) {
		    $cellIterator = $row->getCellIterator();
		    $cellIterator->setIterateOnlyExistingCells(false);
		    $rowIndex = $row->getRowIndex();
			if ($rowIndex > 1){
				$rowIndex = $rowIndex - 2;
			    $array_data[$rowIndex] = array('table_name' => '', 'number' => '', 'manager_username' => '', 'description' => '', 'image' => '');
			
			    foreach ($cellIterator as $cell) {
			        if ('A' == $cell->getColumn()) {
			            $array_data[$rowIndex]['table_name'] = $cell->getCalculatedValue();
			        } else if ('B' == $cell->getColumn()) {
			            $array_data[$rowIndex]['number'] = $cell->getCalculatedValue();
			        } else if ('C' == $cell->getColumn()) {
			            $array_data[$rowIndex]['manager_username'] = $cell->getCalculatedValue();
			        } else if ('D' == $cell->getColumn()) {
			            $array_data[$rowIndex]['description'] = $cell->getCalculatedValue();
			        } else if ('E' == $cell->getColumn()) {
			            $array_data[$rowIndex]['image'] = $cell->getCalculatedValue();
			        }
			    }
			}
		}

		foreach ($array_data as $value) {
			if ($this->is_can_add($value)){
				$this->add_table($value);
			}
		}
		
		redirect("table");
	}
	
	private function is_can_add($table){		
		if(strlen($table['table_name']) < 1){
			return false;
		}
		
		if (strlen($table['number']) > 0){
			if (!is_numeric($table['number'])){
				return false;
			}
		}else{
			return false;
		}
		return true;
	}
	
	private function add_table($table){
		$table['manager_id'] = $this->table->get_manager_id($table['manager_username']);
		unset($table['manager_username']);
		$tmp_name = $table['image'];
		if (strlen($table['image']) > 0){
			$name = (explode(".",$tmp_name));
			$name = Word::Link($table['table_name']).".".strtolower($name[1]);
			$table['image'] = $name;
		}
		
		$table['status'] = 1;
		$result = $this->table->create_new_table($table);
		if ($result != false){
			if (strlen($tmp_name)){
				$url = explode("index.php", $_SERVER['PHP_SELF']);
				$inputFileName = $_SERVER['DOCUMENT_ROOT'].$url[0]."file_upload/table/image/".$tmp_name;
				echo $inputFileName;
				$path = $_SERVER['DOCUMENT_ROOT'].$url[0]."assets/img/table";
				if (file_exists($inputFileName)){
					echo "yesss";
				}
				copy($inputFileName, $path."/".$name);
				$this->add_zip_file($name);
			}
		}
	}
}